//! Start 任务处理
//!

use sgs_core::preclude::Role;
use sgs_runtime::{
    executor::{Controller, Event, Start, Viewer},
    preclude::Delegate,
    random_list, resolve_from,
};

/// 启动事件委托器
///
/// 启动初始化委托器
///
/// 处理所有 [Start] 事件
pub struct StartDelegator;

impl std::fmt::Debug for StartDelegator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "标准包启动事件委托器[sgs_pkg_std::StartDelegator]")
    }
}

impl Delegate for StartDelegator {
    fn delegate(
        &self,
        event: &Event,
        viewer: &Viewer,
        controller: &mut Controller,
    ) -> Option<Event> {
        match event {
            Event::Start(event) => delegate(event, viewer, controller),
            _ => None,
        }
    }
}

/// Start 事件处理
pub fn delegate(event: &Start, viewer: &Viewer, controller: &mut Controller) -> Option<Event> {
    match event {
        Start::Begin => Some(Start::Role.into()),
        Start::Role => {
            let random_list = random_list!(controller.players.len());
            let random_roles: Vec<&Role> = resolve_from!(random_list => viewer.roles);

            for (i, players) in controller.players.iter_mut().enumerate() {
                players.role = random_roles[i].clone();
            }
            Some(Start::HP.into())
        }

        Start::HP => {
            for players in controller.players.iter_mut() {
                if players.identity.is_lord() {
                    players.role.max_hp += 1;
                    players.role.hp += 1;
                    break;
                }
            }
            Some(Start::Card.into())
        }
        _ => None,
    }
}
